import { defineComponent, ref, toRefs, nextTick, watch, onMounted, toRaw, onBeforeUnmount } from 'vue';
import type { PropType } from 'vue';
import { storeToRefs } from 'pinia';

import editor from '@wf/components/bpmnjs/store/editor';
import modulesAndModdle from '@wf/components/bpmnjs/components/Designer/modulesAndModdle';
import initModeler from '@wf/components/bpmnjs/components/Designer/initModeler';
import Linter from '@wf/components/bpmnjs/components/Linter/index.vue';
import { createNewDiagram } from '@wf/components/bpmnjs/utils';

const Designer = defineComponent({
  name: 'BpmnDesigner',
  props: {
    xml: {
      type: String as PropType<string>,
      default: undefined
    },
    config: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['update:xml', 'command-stack-changed'],
  setup(props, { emit }) {
    const editorStore = editor();
    const { editorSettings } = storeToRefs(editorStore);
    const { xml, config } = toRefs(props);
    const designer = ref<HTMLDivElement | null>(null);

    // onMounted(async ()=>{
    //   try {
    //     editorStore.updateConfiguration(config.value)
    //   } catch (e) {
    //     console.log(e)
    //   }
    // })

    const watchEditorSettings = watch(
      () => editorSettings.value,
      async (value, oldValue) => {
        try {
          console.log('调用初始化Designer');
          const modelerModules = modulesAndModdle(editorSettings);
          await nextTick();
          await initModeler(designer, modelerModules, emit);
          await createNewDiagram(toRaw(xml.value), editorSettings.value);
          // if (!xml.value) {
          //   await createNewDiagram(undefined, value)
          // } else {
          //   await createNewDiagram(xml.value, value)
          // }
        } catch (e) {
          console.log(e);
        }
      },
      { deep: true, immediate: true }
    );

    const watchConfig = watch(
      // 由于config和xml同步修改，现在只监听config
      () => props.config,
      (value) => {
        editorStore.updateConfiguration(toRaw(value));
      },
      { deep: true }
    );

    onBeforeUnmount(() => {
      console.log('执行了销毁监听');
      watchEditorSettings();
      watchConfig();
    });

    return () => <div ref={designer} class="designer">
      <Linter />
    </div>;
  }
});

export default Designer;
